import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import {
  Card,
  Button,
  Form,
  Row,
  Col,
  Input,
  Spin,
  BackTop,
  Select,
  DatePicker,
  notification,
  Icon,
  Popover,
  Affix,
} from 'antd';
import moment from 'moment';

import { refitFieldDecoratorOption, refitCommonData } from '../../../utils/tools';
import styles from './BasicInfo.less';

// const { TextArea } = Input;
const FormItem = Form.Item;
// const { MonthPicker } = DatePicker;

const fieldLabels = {
  chvnickname: '用户昵称',
  consumerType: '代理商级别',
  superiorId: '用户上级',
  phone: '联系电话',
  password: '登陆密码',
  rePassword: '确认密码',
  idCard: '身份证号',
  headPortraits: '头像信息',
  email: '邮箱账户',
  birthDate: '生日日期',
  gender: '会员性别',
  province: '省份城市',
  address: '详细地址',
  orderMessage: '订单消息',
  administrationAuthority: '开启管理权限',
};

@connect(({ consumer, global, loading }) => ({
  consumer,
  global,
  loading: loading.models.consumer,
}))
@Form.create()
class BasicInfo extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      // width: '100%',
      metaData: {},
      dataLoading: true,
      saving: false,
    };
  }

  componentDidMount() {
    this.isMountedFlag = true;

    const { match } = this.props;
    const { params } = match;
    const { id: consumerId } = params;

    this.loadData(consumerId);
  }

  consumerTypeList = () => {
    const { global } = this.props;
    return refitCommonData(global.consumerTypeList);
  };

  genderList = () => {
    const { global } = this.props;
    return refitCommonData(global.genderList);
  };

  orderMessageList = () => [{ flag: 0, name: '不接受' }, { flag: 1, name: '接受' }];

  administrationAuthorityList = () => [{ flag: 0, name: '关闭' }, { flag: 1, name: '开启' }];

  loadData = id => {
    const { dispatch } = this.props;

    this.setState({ dataLoading: true }, () => {
      dispatch({
        type: 'consumer/get',
        payload: {
          prodictid: id,
        },
      }).then(() => {
        if (this.isMountedFlag) {
          const {
            consumer: {
              data: { data },
            },
          } = this.props;

          this.setState({ dataLoading: false, metaData: data });
        }
      });
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    const {
      dispatch,
      form,
      location: { pathname },
    } = this.props;
    const { metaData } = this.state;
    form.validateFields((err, values) => {
      if (!err) {
        this.setState({ saving: true });
        const submitValue = values;
        submitValue.province = metaData.province;

        dispatch({
          type: 'consumer/updateBasicInfo',
          payload: submitValue,
        }).then(() => {
          this.setState({ saving: false });
          const {
            consumer: { data },
          } = this.props;
          const { code, message: messageText } = data;
          if (code === 200) {
            notification.success({
              placement: 'bottomRight',
              message: '操作结果',
              description: '数据已经保存成功，请进行后续操作。',
            });
          } else {
            notification.error({
              placement: 'bottomRight',
              message: '操作结果',
              description: messageText,
            });
          }

          dispatch(
            routerRedux.replace({
              pathname: `${pathname.replace('/load/', '/update/')}`,
            })
          );
        });
      }
    });
  };

  buildFieldDescription = (v, op, other) => {
    const o = (other || '') === '' ? '' : `,${other}`;
    return `请${op || '输入'}${v}${o}!`;
  };

  handleFormReset = () => {
    const { dispatch, form } = this.props;
    form.resetFields();
    dispatch({
      type: 'consumer/getCurrent',
      payload: {},
    }).then(() => {
      const {
        consumer: { data },
      } = this.props;
      this.setState({ metaData: data });
      this.setState({ saving: false });
    });
  };

  getErrorInfo = () => {
    const {
      form: { getFieldsError },
    } = this.props;
    const errors = getFieldsError();
    const errorCount = Object.keys(errors).filter(key => errors[key]).length;
    if (!errors || errorCount === 0) {
      return null;
    }
    const scrollToField = fieldKey => {
      const labelNode = document.querySelector(`label[for="${fieldKey}"]`);
      if (labelNode) {
        labelNode.scrollIntoView(true);
      }
    };
    const errorList = Object.keys(errors).map(key => {
      if (!errors[key]) {
        return null;
      }
      return (
        <li key={key} className={styles.errorListItem} onClick={() => scrollToField(key)}>
          <Icon type="cross-circle-o" className={styles.errorIcon} />
          <div className={styles.errorMessage}>{errors[key][0]}</div>
          <div className={styles.errorField}>{fieldLabels[key]}</div>
        </li>
      );
    });
    return (
      <span className={styles.errorIcon}>
        <Popover
          title="表单校验信息"
          content={errorList}
          overlayClassName={styles.errorPopover}
          trigger="click"
          getPopupContainer={trigger => trigger.parentNode}
        >
          <Icon type="exclamation-circle" />
        </Popover>
        {errorCount}
      </span>
    );
  };

  // resizeFooterToolbar = () => {
  //   requestAnimationFrame(() => {
  //     const sider = document.querySelectorAll('.ant-layout-sider')[0];
  //     if (sider) {
  //       const width = `calc(100% - ${sider.style.width})`;
  //       const { width: stateWidth } = this.state;
  //       if (stateWidth !== width) {
  //         this.setState({ width });
  //       }
  //     }
  //   });
  // };

  validate = () => {
    const {
      form: { validateFieldsAndScroll },
      dispatch,
      location: { pathname },
    } = this.props;
    const { metaData } = this.state;

    validateFieldsAndScroll((error, values) => {
      if (!error) {
        this.setState({ saving: true });
        const submitValue = values;
        submitValue.province = metaData.province;

        dispatch({
          type: 'consumer/updateBasicInfo',
          payload: submitValue,
        }).then(() => {
          const {
            consumer: { data },
          } = this.props;
          const { code } = data;
          if (code === 200) {
            notification.success({
              placement: 'bottomRight',
              message: '操作结果',
              description: '数据已经保存成功，请进行后续操作。',
            });
          }

          this.setState({ saving: false }, () => {
            dispatch(
              routerRedux.replace({
                pathname: `${pathname.replace('/load/', '/update/')}`,
              })
            );
          });
        });
      }
    });
  };

  render() {
    const { form } = this.props;
    const {
      metaData,
      saving,
      //  width,
      dataLoading,
    } = this.state;
    const { getFieldDecorator } = form;

    const consumerTypeData = this.consumerTypeList();
    const consumerTypeOption = [];

    consumerTypeData.forEach(item => {
      const { name, flag } = item;
      consumerTypeOption.push(
        <Select.Option key={flag} value={flag}>
          {name}
        </Select.Option>
      );
    });

    const genderData = this.genderList();
    const genderOption = [];

    genderData.forEach(item => {
      const { name, flag } = item;
      genderOption.push(
        <Select.Option key={flag} value={flag}>
          {name}
        </Select.Option>
      );
    });

    const orderMessageData = this.orderMessageList();
    const orderMessageOption = [];

    orderMessageData.forEach(item => {
      const { name, flag } = item;
      orderMessageOption.push(
        <Select.Option key={flag} value={flag}>
          {name}
        </Select.Option>
      );
    });

    const administrationAuthorityData = this.administrationAuthorityList();
    const administrationAuthorityOption = [];

    administrationAuthorityData.forEach(item => {
      const { name, flag } = item;
      administrationAuthorityOption.push(
        <Select.Option key={flag} value={flag}>
          {name}
        </Select.Option>
      );
    });

    return (
      <Fragment>
        <div className={styles.containorBox}>
          <Card
            title="用户基本信息"
            className={styles.card}
            bordered={false}
            extra={
              <Affix offsetTop={20}>
                {this.getErrorInfo()}
                <Button
                  type="primary"
                  icon="save"
                  disabled={dataLoading}
                  // onClick={this.handleSaveBasicInfo}
                  onClick={this.validate}
                  loading={saving}
                >
                  保存
                </Button>
              </Affix>
            }
          >
            <Spin spinning={dataLoading || saving}>
              <Form layout="vertical">
                <Row gutter={24}>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.chvnickname}>
                      {getFieldDecorator(
                        'chvnickname',
                        refitFieldDecoratorOption(metaData.chvnickname, metaData.chvnickname, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.chvnickname),
                            },
                          ],
                        })
                      )(
                        <Input placeholder={this.buildFieldDescription(fieldLabels.chvnickname)} />
                      )}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.consumerType}>
                      {getFieldDecorator(
                        'consumerType',
                        refitFieldDecoratorOption(
                          metaData.consumerType,
                          metaData.consumerType,
                          '',
                          {
                            rules: [
                              {
                                required: false,
                                message: this.buildFieldDescription(
                                  fieldLabels.consumerType,
                                  '选择'
                                ),
                              },
                            ],
                          }
                        )
                      )(
                        <Select
                          placeholder={this.buildFieldDescription(fieldLabels.consumerType, '选择')}
                          // onChange={handleChange}
                        >
                          {consumerTypeOption}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.superiorId}>
                      {getFieldDecorator(
                        'superiorId',
                        refitFieldDecoratorOption(metaData.superiorId, metaData.superiorId, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.superiorId),
                            },
                          ],
                        })
                      )(<Input placeholder={this.buildFieldDescription(fieldLabels.superiorId)} />)}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.phone}>
                      {getFieldDecorator(
                        'phone',
                        refitFieldDecoratorOption(metaData.phone, metaData.phone, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.phone),
                            },
                          ],
                        })
                      )(<Input placeholder={this.buildFieldDescription(fieldLabels.phone)} />)}
                    </FormItem>
                  </Col>
                </Row>

                <Row gutter={24}>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.idCard}>
                      {getFieldDecorator(
                        'idCard',
                        refitFieldDecoratorOption(metaData.idCard, metaData.idCard, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.idCard, '选择'),
                            },
                          ],
                        })
                      )(
                        <Select
                          placeholder={this.buildFieldDescription(fieldLabels.idCard, '选择')}
                          // onChange={handleChange}
                        >
                          {consumerTypeOption}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.email}>
                      {getFieldDecorator(
                        'email',
                        refitFieldDecoratorOption(metaData.email, metaData.email, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.email),
                            },
                          ],
                        })
                      )(<Input placeholder={this.buildFieldDescription(fieldLabels.email)} />)}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.birthDate}>
                      {getFieldDecorator(
                        'birthDate',
                        refitFieldDecoratorOption(
                          metaData.birthDate,
                          metaData.birthDate,
                          '',
                          {
                            rules: [
                              {
                                required: false,
                                message: this.buildFieldDescription(fieldLabels.birthDate),
                              },
                            ],
                          },
                          v => moment(v || '')
                        )
                      )(
                        <DatePicker
                          style={{ width: '100%' }}
                          format="YYYY-MM-DD"
                          placeholder={this.buildFieldDescription(fieldLabels.birthDate)}
                        />
                      )}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.gender}>
                      {getFieldDecorator(
                        'gender',
                        refitFieldDecoratorOption(metaData.gender, metaData.gender, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.gender, '选择'),
                            },
                          ],
                        })
                      )(
                        <Select
                          placeholder={this.buildFieldDescription(fieldLabels.gender, '选择')}
                          // onChange={handleChange}
                        >
                          {genderOption}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                </Row>
                <Row gutter={24}>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.province}>
                      {getFieldDecorator(
                        'province',
                        refitFieldDecoratorOption(metaData.province, metaData.province, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.province, '选择'),
                            },
                          ],
                        })
                      )(
                        <Select
                          placeholder={this.buildFieldDescription(
                            fieldLabels.headPortraits,
                            '选择'
                          )}
                        >
                          {[]}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col lg={18} md={12} sm={24}>
                    <FormItem label={fieldLabels.address}>
                      {getFieldDecorator(
                        'address',
                        refitFieldDecoratorOption(metaData.address, metaData.address, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.address),
                            },
                          ],
                        })
                      )(<Input placeholder={this.buildFieldDescription(fieldLabels.address)} />)}
                    </FormItem>
                  </Col>
                </Row>
              </Form>
            </Spin>
          </Card>
          <Card title="设置头像" className={styles.card} bordered={false}>
            <Spin spinning={dataLoading || saving}>
              <Form layout="vertical" />
            </Spin>
          </Card>
          <Card title="设置密码" className={styles.card} bordered={false}>
            <Spin spinning={dataLoading || saving}>
              <Form className="ant-advanced-search-form">
                <Row gutter={24}>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.password}>
                      {getFieldDecorator(
                        'password',
                        refitFieldDecoratorOption(metaData.password, metaData.password, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.password),
                            },
                          ],
                        })
                      )(<Input placeholder={this.buildFieldDescription(fieldLabels.password)} />)}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.rePassword}>
                      {getFieldDecorator(
                        'rePassword',
                        refitFieldDecoratorOption(metaData.rePassword, metaData.rePassword, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.rePassword, '选择'),
                            },
                          ],
                        })
                      )(<Input placeholder={this.buildFieldDescription(fieldLabels.rePassword)} />)}
                    </FormItem>
                  </Col>
                </Row>
              </Form>
            </Spin>
          </Card>
          <Card title="其他设置" className={styles.card} bordered={false}>
            <Spin spinning={dataLoading || saving}>
              <Form layout="vertical">
                <Row gutter={16}>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.orderMessage}>
                      {getFieldDecorator(
                        'orderMessage',
                        refitFieldDecoratorOption(metaData.orderMessage, metaData.orderMessage, 0, {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.orderMessage),
                            },
                          ],
                        })
                      )(
                        <Select
                          placeholder={this.buildFieldDescription(fieldLabels.orderMessage, '选择')}
                        >
                          {orderMessageOption}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.administrationAuthority}>
                      {getFieldDecorator(
                        'administrationAuthority',
                        refitFieldDecoratorOption(
                          metaData.administrationAuthority,
                          metaData.administrationAuthority,
                          0,
                          {
                            rules: [
                              {
                                required: false,
                                message: this.buildFieldDescription(
                                  fieldLabels.administrationAuthority,
                                  '选择'
                                ),
                              },
                            ],
                          }
                        )
                      )(
                        <Select
                          placeholder={this.buildFieldDescription(
                            fieldLabels.administrationAuthority,
                            '选择'
                          )}
                        >
                          {administrationAuthorityOption}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                </Row>
              </Form>
            </Spin>
          </Card>
        </div>
        <BackTop />
      </Fragment>
    );
  }
}

export default BasicInfo;
